package me.zhengjie.modules.security.security.vo;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.allwees.bs.core.modelbase.branch.BranchUser;
import com.allwees.bs.core.modelbase.branch.EBranchType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.collections.SetUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class JwtUser implements UserDetails, BranchUser {
    private Long id;

    private String uuid;

    private String username;

    private String nickName;

    private String sex;

    @JsonIgnore
    @JSONField(serialize = false)
    private String password;

    private String avatar;

    private String email;

    private String phone;

    private String dept;

    private String job;

    @JsonIgnore
    @JSONField(serialize = false)
    private Collection<GrantedAuthority> authorities;

    private boolean enabled;

    private Timestamp createTime;

    private String[] roleNames;

    @JsonIgnore
    @JSONField(serialize = false)
    private Date lastPasswordResetDate;

    private EBranchType branchType;

    private String branchUuid;

    private String storeUuid;

    private Boolean registered;

    private Boolean shopCreated;

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    public Collection getRoles() {
        return authorities == null ? SetUtils.EMPTY_SET
        		: authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
    }

    /**
     * 用于JWT的自定义claim参数
     *
     * @return
     */
    public JwtUser claimUser() {
 	   return new JwtUser()
 			   .setUuid(getUuid())
 			   .setUsername(getUsername())
               .setEmail(getEmail())
               .setPhone(getPhone())
 			   .setBranchUuid(getBranchUuid())
 			   .setBranchType(getBranchType())
               .setStoreUuid(getStoreUuid())
 			   .setEnabled(isEnabled())
 			   .setRoleNames(getRoleNames());
    }
}
